# Path to your oh-my-zsh installation.

###############################
# OS operation
###############################
if [ "$OS" = "Windows_NT" ]; then
    cd $HOME 2>/dev/null

    export REALHOME="$(cmd /c chdir | sed "s/.$//")"

    function zpty()
    {
        return 0
    }

    export PATH="/usr/bin:$PATH"
    export PATH="/usr/local/bin:$PATH"
    export GOPATH="$REALHOME\\go"
    export EDITOR=vim
fi

if [ "$DISPLAY" = "" ] && [ "$(tty)" = "/dev/tty1" ]; then
    exec startx
fi

###############################
# zsh setting
###############################

export ZSH="$HOME/.oh-my-zsh"
export ZSH_CUSTOM="$ZSH/custom"
export ZPLUG_HOME="$HOME/.config/zplug"
export TERM=xterm-256color

HISTFILE=$HOME/.zsh_history
HISTSIZE=10000000
SAVEHIST=10000000

###############################
# is remote ?
###############################
remote=0
ip_addr=$(who am i | sed 's/.*(\(.*\))/\1/')
who am i >/dev/null 2>&1
if [[ "$?" == "0" ]]; then
    who am i | grep pts
    if [[ "$?" == "0" ]]; then
        # remote
        echo "Welcome, SSH_USER from $ip_addr"
        remote=1
    fi
fi

###############################
# zsh plugins
###############################

plugins=(git zsh-syntax-highlighting h)
plugins+=(zsh-autosuggestions)
if [[ "$0" =~ zsh ]]; then
    if ! [ -e $ZSH_CUSTOM/dracula.zsh-theme ]; then
        source $ZPLUG_HOME/init.zsh
        zplug 'dracula/zsh', as:theme
        zplug 'zsh-users/zsh-syntax-highlighting'
        zplug 'zsh-users/zsh-autosuggestions'
        zplug 'YouDad/h'
        zplug install
        ln -sf $ZPLUG_HOME/repos/dracula/zsh/dracula.zsh-theme $ZSH_CUSTOM/
        function install_zsh_plugin() { ln -sf $ZPLUG_HOME/repos/$1/$2 $ZSH_CUSTOM/plugins/$2; }
        install_zsh_plugin zsh-users zsh-syntax-highlighting
        install_zsh_plugin zsh-users zsh-autosuggestions
        install_zsh_plugin YouDad h
        unset -f install_zsh_plugin
    fi

    ###############################
    # theme
    ###############################
    if [ -e $ZSH_CUSTOM/dracula.zsh-theme ]; then
        ZSH_THEME="dracula"
        DRACULA_DISPLAY_CONTEXT=1
    else
        ZSH_THEME="risto"
    fi

    # Set list of themes to pick from when loading at random
    # Setting this variable when ZSH_THEME=random will cause zsh to load
    # a theme from this variable instead of looking in ~/.oh-my-zsh/themes/
    # If set to an empty array, this variable will have no effect.
    # ZSH_THEME_RANDOM_CANDIDATES=( "robbyrussell" "agnoster" )

    # Uncomment the following line to use case-sensitive completion.
    # CASE_SENSITIVE="true"

    # Uncomment the following line to use hyphen-insensitive completion.
    # Case-sensitive completion must be off. _ and - will be interchangeable.
    # HYPHEN_INSENSITIVE="true"

    # Uncomment the following line to disable bi-weekly auto-update checks.
    # DISABLE_AUTO_UPDATE="true"

    # Uncomment the following line to automatically update without prompting.
    # DISABLE_UPDATE_PROMPT="true"

    # Uncomment the following line to change how often to auto-update (in days).
    # export UPDATE_ZSH_DAYS=13

    # Uncomment the following line if pasting URLs and other text is messed up.
    # DISABLE_MAGIC_FUNCTIONS=true

    # Uncomment the following line to disable colors in ls.
    # DISABLE_LS_COLORS="true"

    # Uncomment the following line to disable auto-setting terminal title.
    # DISABLE_AUTO_TITLE="true"

    # Uncomment the following line to enable command auto-correction.
    # ENABLE_CORRECTION="true"

    # Uncomment the following line to display red dots whilst waiting for completion.
    # COMPLETION_WAITING_DOTS="true"

    # Uncomment the following line if you want to disable marking untracked files
    # under VCS as dirty. This makes repository status check for large repositories
    # much, much faster.
    # DISABLE_UNTRACKED_FILES_DIRTY="true"

    # Uncomment the following line if you want to change the command execution time
    # stamp shown in the history command output.
    # You can set one of the optional three formats:
    # "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd"
    # or set a custom format using the strftime function format specifications,
    # see 'man strftime' for details.
    # HIST_STAMPS="mm/dd/yyyy"

    # Would you like to use another custom folder than $ZSH/custom?
    # ZSH_CUSTOM=/path/to/new-custom-folder

    # Which plugins would you like to load?
    # Standard plugins can be found in ~/.oh-my-zsh/plugins/*
    # Custom plugins may be added to ~/.oh-my-zsh/custom/plugins/
    # Example format: plugins=(rails git textmate ruby lighthouse)
    # Add wisely, as too many plugins slow down shell startup.

    source $ZSH/oh-my-zsh.sh

    ###############################
    # opt
    ###############################

    setopt inc_append_history
    unsetopt auto_cd
fi

# User configuration

# export MANPATH="/usr/local/man:$MANPATH"

# You may need to manually set your language environment
# export LANG=en_US.UTF-8

# Preferred editor for local and remote sessions
# if [[ -n $SSH_CONNECTION ]]; then
#   export EDITOR='vim'
# else
#   export EDITOR='mvim'
# fi

# Compilation flags
# export ARCHFLAGS="-arch x86_64"

# Set personal aliases, overriding those provided by oh-my-zsh libs,
# plugins, and themes. Aliases can be placed here, though oh-my-zsh
# users are encouraged to define aliases within the ZSH_CUSTOM folder.
# For a full list of active aliases, run `alias`.
#
# Example aliases
# alias zshconfig="mate ~/.zshrc"
# alias ohmyzsh="mate ~/.oh-my-zsh"

###############################
# user set
###############################
umask 022

###############################
# alias command
###############################
function try_alias()
{
    if which "${1%%=*}" 1>/dev/null 2>&1; then
        return 0
    fi
    alias "$1"
}

try_alias gvv="git status -vv"
try_alias grs="git restore --staged"
try_alias gbmv="git branch --move"
try_alias gs="git status"
try_alias gpod="git push origin --delete"
try_alias gaf="git add -f"
try_alias gfp="git format-patch"
try_alias ra="ranger"
try_alias lg="lazygit"
try_alias ta="tig --all"

alias sudo="sudo -E"
alias mkdir="mkdir -p "

###############################
# export
###############################
export QT_QPA_PLATFORMTHEME="qt5ct"
export GTK_IM_MODULE=fcitx
export QT_IM_MODULE=fcitx
export XMODIFIERS="@im=fcitx"

export PATH="$HOME/my/libs:$PATH"
export PATH="$HOME/my/bin:$PATH"
export PATH="$HOME/bin:$PATH"
export PATH="$HOME/.local/bin:$PATH"
export PATH="$HOME/.yarn/bin:$PATH"
export PATH="$HOME/.config/crepo:$PATH"

if [ -d "$HOME/repos/android_sdk/build-tools" ]; then
    for version in $(ls $HOME/repos/android_sdk/build-tools); do
        export PATH="$PATH:$HOME/repos/android_sdk/build-tools/$version"
    done
fi

### GO
[ "$GOPATH" = "" ] && export GOPATH="$HOME/go"
export PATH="$PATH:$GOPATH/bin"
export GO111MODULE=on
export GOPROXY=https://goproxy.cn

export TMOUT=1000000
[ "$EDITOR" != "vim" ] && export EDITOR=vim
export LD_PRELOAD=""

### Dart
export PATH="$PATH":"$HOME/.pub-cache/bin"
export PUB_HOSTED_URL=https://mirrors.tuna.tsinghua.edu.cn/dart-pub
export FLUTTER_STORAGE_BASE_URL=https://mirrors.tuna.tsinghua.edu.cn/flutter

### Wine
export WINEARCH=win32

### Electron
export ELECTRON_MIRROR=http://npm.taobao.org/mirrors/electron/

### Java
if [ "$JAVA_HOME" = "" ]; then
    for f in $(ls -r /usr/lib/jvm); do
        if [ -e /usr/lib/jvm/$f/include ]; then
            export JAVA_HOME=/usr/lib/jvm/$f
            break
        fi
    done
    unset f
fi

if [ "$JAVA_HOME" = "" ]; then
    for f in $(ls -r /usr/lib/jvm); do
        if [ -e /usr/lib/jvm/$f/bin ]; then
            export JAVA_HOME=/usr/lib/jvm/$f
            break
        fi
    done
    unset f
fi

### Android SDK
export ANDROID_SDK="$HOME/repos/android_sdk"
export ANDROID_SDK_HOME="$HOME/repos/android_sdk"
export ANDROID_NDK_HOME="$HOME/repos/android_sdk/android-ndk-r14b"

### NonRoot Python
export LUWH_NONROOT_PYTHON_PATH="$HOME/.config/non_root_python"
export PYTHONPATH="$PYTHONPATH:$LUWH_NONROOT_PYTHON_PATH"
if [ ! -e "$LUWH_NONROOT_PYTHON_PATH" ]; then
    mkdir -p "$LUWH_NONROOT_PYTHON_PATH"
fi

function pipinstall_nonroot()
{
    local PIP=pip
    if ! which $PIP 2>/dev/null; then
        PIP=pip3
    fi
    if ! which $PIP 2>/dev/null; then
        echo no pip or pip3
        return 1
    fi

    $PIP install "$@" --target="$LUWH_NONROOT_PYTHON_PATH"
}

### FakeRoot
export FAKEROOT_PATH="$HOME/.config/fake_root"
export PATH="$FAKEROOT_PATH/bin:$PATH"
export PATH="$FAKEROOT_PATH/usr/bin:$PATH"
export PATH="$FAKEROOT_PATH/usr/lib/git-core:$PATH"
export LD_LIBRARY_PATH="$FAKEROOT_PATH/lib:$LD_LIBRARY_PATH"
export LD_LIBRARY_PATH="$FAKEROOT_PATH/usr/lib:$LD_LIBRARY_PATH"

function izst()
{
    ({
        cd ~/Downloads/package
        wget -c $1 || exit
        name=$(basename $1)
        unzstd $name || exit
        tar axf ${name%.*} -C $FAKEROOT_PATH || exit
        rm ${name%.*} || exit
    })
}

function patch_interpreter()
{
    patchelf --set-interpreter $FAKEROOT_PATH/usr/lib/ld-linux-x86-64.so.2 $(realpath $(which $1))
}

function patch_needed()
{
    local libname="$2"
    libname+="${libname:$((${#libname}-1)):1}"
    libname+="${libname:$((${#libname}-1)):1}"
    libname+="${libname:$((${#libname}-1)):1}"
    patchelf --replace-needed $2 $libname $(realpath $(which $1))
}

function efr()
{
    export FAKEROOT_PATH="$HOME/.config/fakeroot"
    export PATH="$FAKEROOT_PATH/bin:$PATH"
    export PATH="$FAKEROOT_PATH/usr/bin:$PATH"
    export LD_LIBRARY_PATH="$FAKEROOT_PATH/lib:$LD_LIBRARY_PATH"
    export LD_LIBRARY_PATH="$FAKEROOT_PATH/usr/lib:$LD_LIBRARY_PATH"
}

###############################
# source
###############################

### FZF installed by $(git clone https://github.com/junegunn/fzf) and pacman -S fzf
if [ -e $HOME/.fzf ]; then
    [[ "$-" == "*i*" ]] && source "$HOME/.fzf/shell/completion.zsh" 2>/dev/null
    source "$HOME/.fzf/shell/key-bindings.zsh"
fi

if [ -e /usr/share/fzf ]; then
    [[ "$-" == "*i*" ]] && source "/usr/share/fzf/completion.zsh" 2>/dev/null
    source "/usr/share/fzf/key-bindings.zsh"
fi

### HHISTORY
if [[ "$0" =~ zsh ]] && [ -f $HOME/my/src/hhistory/hhistory.sh ]; then
    source $HOME/my/src/hhistory/hhistory.sh
fi

### env
if [ -e $HOME/env ]; then
    source $HOME/env
fi

###############################
# function
###############################

function wiki() {
    if [ -e  ~/my/link/wiki ]; then
        cd ~/my/link/wiki
        vim README.md
    else
        echo no wiki link
    fi
}

function cdd() {
    if [ -d "$1" ]; then
        cd "$1"
    else
        cd "$(dirname $1)"
    fi
}

function retmux() {
    tmux -2 has-session -t $1 2>/dev/null
    if [[ "$?" == "0" ]]; then
        tmux -2 attach-session -t $1
    else
        tmux -2 new-session -t $1
    fi
}

function adbrrp() {
    adb wait-for-device root && \
        adb wait-for-device remount && \
        adb wait-for-device push $1 $2
}

function ffhelp() {
    ffmpeg -hide_banner -h filter=$1
}

function ffgrep() {
    ffmpeg -hide_banner -filters | grep $*
}

function errno() {
    egrep '^#define\s[A-Z]*\s\s*'$1'\s' /usr/include/asm-generic/errno-base.h /usr/include/asm-generic/errno.h
}

function cat_dtb() {
    dtc -Idtb -Odts $1
}

function auto_generate_uml() {
    set -x
    plantuml $1
    feh $(sed 's/.uml/.png/' <<< $1) &
    while true; do
        inotifywait -e modify $1
        plantuml $1
    done
    set +x
}

function pacman_fixfile()
{
    set -x
    local package="$(sudo pacman -F $1 | awk '{print $5}')"
    sudo pacman -S --noconfirm $package 1>/dev/null 2>&1
    rm_pacman_exist $package
    sudo pacman -S --noconfirm $package
    set +x
}

function rm_pacman_exist()
{
    sudo pacman -S --noconfirm $1 2>&1 | grep "exists in filesystem" | awk '{print $2}' | xargs sudo rm -f
}

###############################
# tmux
###############################

if [[ "$remote" == "1" ]]; then
    if [ -e $HOME/.tmux_ip_enable ]; then
        if [[ "$TMUX" == "" ]]; then
            session_name=$(echo $ip_addr | cut -d '.' -f 3-4 | sed 's/\./_/g')
            session_name=" ${session_name} "
            tmux -2 has-session -t "$session_name" 2>/dev/null
            if [[ "$?" != "0" ]]; then
                tmux -2 new-session -t "$session_name" 2>/dev/null
            else
                tmux -2 attach-session -t "$session_name" 2>/dev/null
            fi

            exit
        fi
    elif [ -e $HOME/.tmux_share_enable ]; then
        if [[ "$TMUX" == "" ]]; then
            session_name=" ssh "
            tmux -2 has-session -t "$session_name" 2>/dev/null
            if [[ "$?" != "0" ]]; then
                tmux -2 new-session -t "$session_name" 2>/dev/null
            else
                tmux -2 attach-session -t "$session_name" 2>/dev/null
            fi

            exit
        fi
    fi
else
    if [ -e $HOME/.tmux_local_enable ]; then
        if [[ "$TMUX" == "" ]]; then
            session_name=$(echo $TTY | cut -d '/' -f 3- | sed 's/\//_/g')
            session_name=" ${session_name} "
            tmux -2 has-session -t "$session_name" 2>/dev/null
            if [[ "$?" != "0" ]]; then
                tmux -2 new-session -t "$session_name" 2>/dev/null
            else
                tmux -2 attach-session -t "$session_name" 2>/dev/null
            fi

            exit
        fi
    fi
fi

export OHOS_TOOL='/home/luwh/repos/ohos_tool'
if [ -e $OHOS_TOOL ]; then
    export TRACE_FILE="$HOME/analyzing.trace"
    export SHELL_DEBUG=false
    export SHELL_PREF=false
    if $SHELL_PREF; then
        echo "# tracer: nop" > $TRACE_FILE
    fi

    source $OHOS_TOOL/scripts/ohos-tool-env.sh
fi

export DES2_DEBUG_DIR='/home/lf0052/repos/DES2_V1.0_20230310'
ulimit -c unlimited

ls > /dev/null 2>&1
